/*
* * V1.0
* 1、自动拉取过滤规则
* 2、提交过滤规则
* */

let ip = "140.143.131.147"
function send(data) {
    chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
        var activeTab = tabs[0];
        chrome.tabs.sendMessage(activeTab.id, data, (res) => {
            console.log(res)
        });
    });
}

document.querySelector('.update').addEventListener('click', () => {
    fetch(`${ip}/api/keywords`).then(response => response.json())
    .then(data => {
        console.log('获取到的关键词:', data.keywords);

        send({
            type: 'update',
            data: data.keywords
        })

    })
    .catch(error => {
        console.error('获取关键词失败:', error);
        alert('关键词更新失败：' + error.message);
    });
});

document.querySelector('.commit').addEventListener('click', () => {
    let data = document.querySelector("#keyword").value

    if (data == null || data === '') {
        return
    }
    //修改内容脚本屏蔽字典
    send({
        type: 'commit',
        data: data
    })

    //同步数据库
    fetch(`${ip}/api/keywords`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            keyword: data,
        })
    }).then(response => response.json()).then(data => {
        console.log('提交关键词:', data);
    })
    .catch(error => {
        console.error('获取关键词失败:', error);
        alert('关键词更新失败：' + error.message);
    });
});
